<template>
    <div ref="container">
        <div style="padding-left: 10px;">
        <el-button @click='zoomOut' ref="zoomOut">缩小</el-button>
        <el-button @click='zoomIn' ref="zoomIn">放大</el-button>
        <el-button @click="expandAll">全部展开</el-button>
        <el-button @click="unExpandAll">全部收起</el-button>
        <!--<el-button @click="downloadImg">下载图片</el-button>-->
        </div>
        <!--<el-button @click="selectNode">指定选中</el-button>-->
        <div id="jsmind_container" style="width: 100%;height: 80vh;overflow-y: scroll;" ref="jsmindContainer"></div>

        <modal ref="modal_1" :title="title" :isCloseConfirm="false" top="5%" width="50%" height="50%"
            :close-on-click-modal="false" @modalOpened="opened" @modalClose="close">
            <avue-crud :option="option" :table-loading="loading" :data="data" v-model:page="page" v-model:search="search"
                v-model="form" ref="crud1" @row-dblclick="dblclick" @sort-change="sortChange" @search-change="searchChange"
                @search-reset="searchReset" @selection-change="selectionChange" @current-change="currentChange"
                @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoadMaterialNo">
                <template #menu-left>
                    <span style="color:dimgrey; padding-left: 5px; font-size: 12px; display:flex; transform: translateY(100%);">双击即可选择数据</span>
                </template>
                <template #radio="{ row }">
                    <el-radio v-model="selectRow" :label="row.$index">-</el-radio>
                </template>
            </avue-crud>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="addNode">
                        确定
                    </el-button>
                </span>
            </template>
        </modal>
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import '@/styles/jsmind.css'
// import jsMind from 'jsmind/js/jsmind.js'
import { initScreenShot } from '@/utils/jsmind.screenshot.js'
initScreenShot(window)
import { jsmindInit } from '@/utils/jsmind.js'
jsmindInit(window)
// window.jsMind = jsMind
// import.meta.glob('/jsmind/js/jsmind.draggable.js')
// import.meta.glob('/jsmind/js/jsmind.screenshot.js')



import { init } from '@/utils/jsmind.menu.js'
import { getList, getDetail, add, update, remove, getTree, getMaterialNoList, addReturn } from "@/api/anwise/material/material_no_chart";


export default {
    data() {
        return {
            emits: ["success"],
            selectedNode: '',
            form: {},
            query: {},
            loading: true,
            dateFormat: 'YYYY-MM-DD',
            pickerOptions: {},
            page: {
                pageSize: 10,
                currentPage: 1,
                total: 0
            },
            search: {},
            selectionList: [],
            option: {
                height: '100%',
                calcHeight: 30,
                tip: false,
                searchShow: true,
                searchMenuSpan: 6,
                border: true,
                index: true,
                labelWidth: 150,
                indexWidth: 100,
                menu: false,
                menuWidth: 120,
                addBtn: false,
                editBtn: false,
                viewBtn: false,
                delBtn: false,
                searchEnter:true,
                stripe: true,
                searchIndex: 3,
                searchIcon: false,
                highlightCurrentRow: true,
                column: [

                    {
                        label: "编号代码",
                        prop: "codeNo",
                        type: "input",
                        search: true,
                        overHidden: true,
                        sortable: true,
                        rules: [{
                            required: true,
                            message: "请输入编号代码",
                            trigger: "blur"
                        }],
                    },
                    {
                        label: "编号名称",
                        prop: "codeName",
                        type: "input",
                        search: true,
                        overHidden: true,
                        sortable: true,
                        rules: [{
                            required: true,
                            message: "请输入编号名称",
                            trigger: "blur"
                        }],
                    },
                    {
                        label: "备注",
                        prop: "remark",
                        type: "textarea",
                        overHidden: true,
                        sortable: true,
                        span: 24,
                    },
                    {
                        label: "创建人",
                        prop: "createUserName",
                        type: "input",
                        overHidden: true,
                        sortable: true,
                    },
                    {
                        label: "创建时间",
                        prop: "createTime",
                        type: "input",
                        overHidden: true,
                        sortable: true,
                        search: false,
                    },
                ]
            },
            data: [],
            dialogVisible: false,
            mind: {
                meta: {/* 元数据，定义思维导图的名称、作者、版本等信息 */
                    name: 'ztengluo',
                    author: 'hizzgdev@163.com',
                    version: '0.2'
                },
                format: 'node_tree',
                // format: 'node_array',
                data:
                {
                    id: '0',
                    topic: '编号前<br>缀结构',
                    children: [],
                    'background-color': '#409eff'

                },
            },
            jmOptions: {
                container: 'jsmind_container', // [必选] 容器的ID
                editable: true, // [可选] 是否启用编辑
                // theme: 'clouds', // [可选] 主题
                theme: 'primary', // [可选] 主题
                support_html: true,    // 是否支持节点里的HTML元素
                view: {
                    engine: 'canvas',   // 思维导图各节点之间线条的绘制引擎
                    hmargin: 200,        // 思维导图距容器外框的最小水平距离
                    vmargin: 50,         // 思维导图距容器外框的最小垂直距离
                    line_width: 1,       // 思维导图线条的粗细
                    line_color: '#C18AFB'   // 思维导图线条的颜色
                },
                menuOpts: {
                    showMenu: true,
                    switchMidStage: true, //开启中台
                    newNodeText: '新的节点',
                    injectionList: [
                        // {
                        //     target: 'edit', text: '编辑节点',
                        //     callback: function (node) {
                        //         console.log(node)
                        //     }
                        // },
                        {
                            target: 'addChild', text: '添加子节点',
                            // callback: function (node, fn) {
                            //     console.log(node);
                            //     fn('powerful133333333', '刚');

                            // },
                            callback: (node, fn) => {
                                this.selectedNode = this.jm.get_selected_node();
                                console.log(this.selectedNode);
                                this.$refs.modal_1.show();
                                // this.dialogVisible = true
                                // this.options.menuOpts.newNodeText = 'aaaaaaaaaaaaa'
                                // fn('powerful133333333');
                                console.log(node)
                            }
                        },
                        // {
                        //     target: 'addBrother', text: '添加兄弟节点',
                        //     callback: function (node) {
                        //         console.log(node)
                        //     }
                        // },
                        {
                            target: 'delete', text: '删除节点',
                            callback: (node, next) =>{
                                console.log(node)
                                // remove(node.id).then(() => {
                                //     // this.onLoad();
                                //     next(node.id)
                                //     this.$emit("success");
                                //     this.$message({
                                //         type: "success",
                                //         message: "操作成功!"
                                //     });
                                // });
                                this.$confirm("确定将选择节点以及子节点删除?", {
                                    confirmButtonText: "确定",
                                    cancelButtonText: "取消",
                                    type: "warning"
                                })
                                    .then(() => {
                                        return remove(node.id);
                                    })
                                    .then(() => {
                                        // this.onLoad();
                                        this.$emit("success");
                                        next(node.id)
                                        this.$message({
                                            type: "success",
                                            message: "操作成功!"
                                        });
                                    });
                            }
                        },
                        // {
                        //     target: 'screenshot', text: '下载导图',
                        //     callback: function (node, next) {
                        //         console.log(node)
                        //     }
                        // },
                        // {
                        //     target: 'showAll', text: '展开全部节点',
                        //     callback: function (node, next) {
                        //         console.log(node)
                        //     }
                        // },
                        // {
                        //     target: 'hideAll', text: '收起全部节点',
                        //     callback: function (node, next) {
                        //         console.log(node)
                        //     }
                        // },
                    ],
                },
            },
            jm: '',


        };
    },
    mounted() {
        init(window)
        // setTimeout(() => {
        //
        // }, 1000);
        this.onLoad();
    },
    methods: {
        showAdd(node) {
            this.selectedNode = node;
            this.$refs.modal_1.show();
        },
        opened() {
            this.onLoadMaterialNo(this.page);
        },
        close() {

        },
        dblclick(row) {
            console.log(this.selectedNode);
            console.log('@@@@@@@@@@@@@@', row.codeNo, row.codeName, row.id, row);
            let newNode = {
                parentId: this.selectedNode.id,
                codeNo: row.codeNo,
                codeName: row.codeName,
            }
            this.$refs.modal_1.hide();
            addReturn(newNode).then((res) => {
                if (res.data.success) {
                    this.$message({
                        type: "success",
                        message: "添加成功!"
                    });
                    this.jm.select_clear();
                    this.refreshJsMind();

                    // const topic = `<span style="font-size:14px;">[${row.codeNo}]</span><br>${row.codeName}`
                    // const nodeid = new Date().getTime()
                    // this.jm.add_node(this.selectedNode, nodeid, topic)
                    // this.jm.select_node(nodeid);
                    // this.onLoad();
                    this.$emit("success");
                } else {
                    this.$message({
                        type: "error",
                        message: "添加失败!"
                    });
                }
            }, error => {
                window.console.log(error);
            });

        },
        refreshJsMind() {
            getTree().then(res => {
                if (res.data.success) {
                    this.mind.data.children = res.data.data;
                    // console.log('!!!!!!!!!!!!!!',this.mind.data.children);

                    // this.drawMind()

                    this.jm.show( this.mind);
                    const parentIds = this.findParentIds(this.mind.data.children, this.selectedNode.id)
                    parentIds.map(item => {
                        this.jm.expand_node(item)
                    })
                    this.jm.expand_node(this.selectedNode.id)
                }
            })
        },
        sortChange(val) {
            console.log(val)
            this.sort = {
                prop: val.prop,
                order: val.order
            };
            let order = "";
            if (this.sort.prop && this.sort.order) {
                if (this.sort.order === "descending") {
                    order = `${this.sort.prop} desc`
                } else {
                    order = `${this.sort.prop} asc`
                }
            }
            this.query.orderBy = order;
            this.onLoadMaterialNo(this.page);
        },
        searchReset() {
            this.query = {};
            this.search.createTimeSearch = '';;
            this.onLoadMaterialNo(this.page);
        },
        searchChange(params, done) {
            this.query = params;
            this.page.currentPage = 1
            this.onLoadMaterialNo(this.page, params);
            done();
        },
        selectionChange(list) {
            this.selectionList = list;
        },
        selectionClear() {
            this.selectionList = [];
            this.$refs.crud1.toggleSelection();
        },
        currentChange(currentPage) {
            this.page.currentPage = currentPage;
        },
        sizeChange(pageSize) {
            this.page.pageSize = pageSize;
        },
        refreshChange() {
            this.onLoadMaterialNo(this.page, this.query);
        },
        onLoadMaterialNo(page, params = {}) {
            this.loading = true;
            getMaterialNoList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                const data = res.data.data;
                this.page.total = data.total;
                this.data = data.records;
                this.loading = false;
                this.selectionClear();
            });
        },
        handleDbClick(row) {
            const parentIds = this.findParentIds(this.mind.data.children, row.id)
            parentIds.map(item => {
                this.jm.expand_node(item)
            })
            this.jm.select_node(row.id);
            const selectedNode = this.jm.get_selected_node(row.id)
            const x = selectedNode._data.view.abs_x
            const y = selectedNode._data.view.abs_y
            console.log('!!!!!', selectedNode._data);
            this.$refs.jsmindContainer.scrollTo(x, y - 50)
        },
        //获取所有父级id
        findParentIds(dataSource, nodeId) {
            const parentIds = [];
            function traverse(node, nodeId) {
                if (node.id === nodeId) return true;
                if (node.children) {
                    for (const childNode of node.children) {
                        if (traverse(childNode, nodeId)) {
                            parentIds.push(node.id);
                            return true;
                        }
                    }
                }
                return false;
            }
            for (const node of dataSource) {
                if (traverse(node, nodeId)) break;
            }
            return parentIds; // 返回所有父节点ID的数组
        },
        onLoad() {
            getTree().then(res => {
                if (res.data.success) {
                    console.log(res.data)
                    this.mind.data.children = res.data.data;
                    this.mind.data.isroot = true;
                    this.mind.data.isvisible = false;
                    this.drawMind()
                }
            })
        },
        selectNode() {

            this.jm.expand_node(2)
            this.jm.expand_node(88)

            this.jm.select_node(91);
            // this.jm.toggle_node('open2')
        },
        drawMind() {
         //   jsMind.preventMindEventDefault();
            this.jm = new jsMind(this.jmOptions);
            this.jm.show(this.mind);
            window.$vue = this
            document.querySelector('.theme-primary').style.transform = 'scale(0.8)';
            document.querySelector('.jsmind').style.transform = 'scale(0.8)';
            // this.zoomOut();
            // this.zoomOut();
            // this.jm.enable_edit()
            // this.jm.enable_event_handle('dblclick')
        },
        // 缩小
        zoomOut() {
            if (this.jm.view.zoomOut()) {
                this.$refs.zoomOut.disabled = false
            } else {
                this.$refs.zoomOut.disabled = true
            }
        },
        expandAll() {
            this.jm.expand_all();
        },
        unExpandAll() {
            this.jm.collapse_all();
        },
        downloadImg(){
            this.jm.screenshot.shootDownload();
        },
        // 放大
        zoomIn() {
            if (this.jm.view.zoomIn()) {
                this.$refs.zoomIn.disabled = false
            } else {
                this.$refs.zoomIn.disabled = true
            }
        },
        // 新增节点
        addNode() {
            var selectedNode = this.jm.get_selected_node() // as parent of new node
            console.log('selected_node', selectedNode)
            if (!selectedNode) { alert('请先选择一个节点'); return }

            var topic = 'new Node'
            this.jm.add_node(selectedNode, 543254354, topic)
            this.dialogVisible = false
        },
        // 删除节点
        onRemoveNode() {
            var selectedId = this.get_selected_nodeid()
            console.log(selectedId)
            if (!selectedId) { alert('请先选择一个节点'); return }
            this.jm.remove_node(selectedId)
        },
        // 获取选中标签的 ID
        get_selected_nodeid() {
            var selectedNode = this.jm.get_selected_node()
            if (selectedNode) {
                return selectedNode.id
            } else {
                return null
            }
        }
    }
};

</script>

<style>
@keyframes blink {
    0% {
        opacity: 1;
    }

    50% {
        opacity: 0;
    }

    100% {
        opacity: 1;
    }
}

.error {
    animation: blink 3s linear infinite;
    background: red;
}
</style>
